'''
An RPG Modification for Source games using Source Python.

    Copyright (C) 2012 Steven Hartin

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Created on 3 Dec 2012

@author: Steven Hartin
@file: ../sourcerpg/utils/enum.py
'''

__all__ = ["Enum"]


class Enum(object):
    """Abstract class used for all enumerations"""
    def __init__(self, *args, **kwargs):
        super(Enum, self).__init__()
        self.__last_element_index = 0
        if "start" in kwargs:
            self.__last_element_index = kwargs["start"]
        for arg in args:
            setattr(self, arg, self.__last_element_index)
            self.__last_element_index += 1

    def __contains__(self, attr):
        return attr in vars(self).values() or hasattr(self, attr)

    def __getattr__(self, attr):
        # Raise a custom exception note
        raise AttributeError("%s is not a valid value of this enum" %
                                attr)

    def __setattr__(self, attr, value):
        if value is None:
            # Values of None will use the last indexed value
            value = self.__last_element_index
            self.__last_element_index += 1
        if type(value) is not int:
            raise TypeError("Enumerations can only set int attributes, "
                            "received type '%s'" % type(value).__name__)
            if value > self.__last_element_index:
                self.__last_element_index = value
        super(Enum, self).__setattr__(attr, value)

    def __getitem__(self, item):
        return getattr(self, item)

    def __setitem__(self, item, value):
        setattr(self, item, value)
